<?php
/**
 * Stores files in self::$fileDir (ex."files") using unique names on save
 * allowing only one file (substituting)
 */
class PlUploadWidget extends UploadWidget {
    const  UPLOAD_ACTION    = 'upload';
    const  DELETE_ACTION    = 'delete';
    const  FILE_LIST_ACTION = 'fileList';
    const  DEBUG_SESSION_ACTION = 'debugSession';

    private $assetsUrlBase;

    protected function registerScripts() {
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript('jquery');

        // Publish assets
        $assetsDir = dirname(__FILE__).DIRECTORY_SEPARATOR.'assets';

        $this->assetsUrlBase = Yii::app()->getAssetManager()->publish($assetsDir);
        $cs->registerCssFile($this->assetsUrlBase.'/plupload.css');
        $cs->registerScriptFile($this->assetsUrlBase.'/plupload.full.min.js');
        $cs->registerScriptFile($this->assetsUrlBase.'/jquery.tablednd_0_5.js');
        // Register the script for handling swfUploads and its dependencies
        $cs->registerScript('plupload_js',$this->render('plupload_js',
           array(
                'upload_action_url'         => $this->getController()->createUrl(
                $this->getController()->getId().'/'.UploadWidget::PREFIX.PlUploadWidget::UPLOAD_ACTION),
                'file_list_url'             => $this->getController()->createUrl(
                $this->getController()->getId().'/'.UploadWidget::PREFIX.PlUploadWidget::FILE_LIST_ACTION),
                'delete_action_url'         => $this->getController()->createUrl(
                $this->getController()->getId().'/'.UploadWidget::PREFIX.PlUploadWidget::DELETE_ACTION),
                'plupload_flash_swf'        => $this->assetsUrlBase.'/plupload.flash.swf',
                'plupload_silverlight_xap'  => $this->assetsUrlBase.'/plupload.silverlight.xap',
                'fileListId'                => 'fileList',
            ),
            true
        ));
    }

    /** Default view (upload widget) */
    public function run() {
        $this->registerScripts();

        // File list
        // Temporal files in session + files associated to the model
        $tempFiles = array();
        $sessionFiles = Yii::app()->session['temp_files'];
        if (isset($sessionFiles))
            foreach($sessionFiles as $f) $tempFiles[] = File::buildFromArray($f);

        if (isset($this->model)) {
            $files = UploadUtils::findFiles(get_class($this->model), $this->model->getPrimaryKey());
        }
        $files = array_merge($files, $tempFiles);
        $this->getController()->renderPartial('ext.upload.plupload.views.draggableFileList', array('files'=>$files));

        // Upload widget
        $this->render('uploadWidget', array(
            'assetsDir' => $this->assetsUrlBase,
        ));
    }

    public static function actions() {
        return array(
                self::UPLOAD_ACTION => array('class'=>'ext.upload.plupload.actions.UploadAction'),
                self::DELETE_ACTION => array('class'=>'ext.upload.plupload.actions.DeleteAction'),
                self::FILE_LIST_ACTION => array('class'=>'ext.upload.plupload.actions.FileListAction'),
                self::DEBUG_SESSION_ACTION=> array('class'=>'ext.upload.plupload.actions.DebugSessionAction'),
        );
    }



    ///////////////////////////////////////////////////////////////////// Events
    public function events() {
        return array(
                //'onBeforeSave'=>'beforeSave',
                'onAfterSave'=>'afterSave',
                //'onBeforeDelete'=>'beforeDelete',
                'onAfterDelete'=>'afterDelete',
                //'onAfterConstruct'=>'afterConstruct',
                //'onBeforeFind'=>'beforeFind',
                //'onAfterFind'=>'afterFind',
        );
    }

    public function afterSave($event) {
        $model = $this->getOwner();
        $sessionFiles = UploadUtils::getSessionFiles();

        if (isset($_POST['File'])) {
            $files = array();
            foreach($_POST['File'] as $i=>$item) {
                if (isset($_POST['File'][$i])) {
                    $fid = $_POST['File'][$i]['fid'];
                    if ($fid[0]=='s') { // is Session file!!
                        $sid = substr($fid, 1);
                        $file = UploadUtils::getFileFromSession($sid);
                        if (isset($file)) {
                            if (file_exists(self::$tempDir.'/'.$file->filename)) {
                                $oldFileName = $file->filename;
                                $file->filename = UploadUtils::createUniquefilename($file->filename, self::$fileDir);

                                $file->entity= get_class($model);
                                $file->EXid = $model->getPrimaryKey();
                                // Por que??? if (Yii::app()->user->isGuest) $file->status=1;
                                $file->status=1;

                                // Move the temp files to repository
                                if (rename(self::$tempDir.'/'.$oldFileName, self::$fileDir.'/'.$file->filename)) { // Move
                                    $file->save();
                                }
                            }
                        }
                    } else {  // is a file in DB
                        $file = File::model()->findbyPk($fid);
                        $file->attributes = $_POST['File'][$i];
                        $file->save();
                    }

                    $files[] = $file;
                }
            }
        }
        UploadUtils::clearSessionFiles();
    }
    public function afterDelete() {
        UploadUtils::deleteFiles($this->getOwner(), self::$fileDir);
    }

}